package edu.arizona.arid.akshen.entity;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;


/**
 * 
 * @author Sumin Byeon
 */
public final class Message extends Entity {
	/**
	 * Automatically generated serial id
	 */
	private static final long serialVersionUID = -750412494473279500L;

	public enum Type {
		Text,
		LoggedIn,
		LoggedOut,
		KeepAlive,
		ChangeStauts,
		File,
		Exception,
		Notification,
	}
	
	private int id;
	private User user;
	private Type type;
	private Timestamp date;
	private String text;
//	private String sessionId;
	
	public Message() {
	}
	
	public Message(ResultSet rs) throws SQLException {
		
	}
	
	public Message(Type type) {
		setType(type);
	}
	
	public Message(Type type, String message) {
		setType(type);
		setText(message);
	}
	
	public int getId() {
		return id;
	}
	
	public void setId(int id) {
		this.id = id;
	}
	
	public User getUser() {
		return user;
	}
	
	public void setUser(User user) {
		this.user = user;
	}
	
	public Type getType() {
		return type;
	}
	
	public void setType(Type type) {
		this.type = type;
	}
	
	public void setType(String type) {
		this.type = Type.valueOf(type);
	}

	public Timestamp getDate() {
		if(date == null) {
			// no change on this.date
			return new Timestamp(new Date().getTime());
		}
		else {
			return date;
		}
	}

	public void setDate(Timestamp timestamp) {
		this.date = timestamp;
	}
	
	public void setDate(String timestamp) {
		this.date = Timestamp.valueOf(timestamp);
	}

	public String getText() {
		return text;
	}
	
	public void setText(String message) {
		this.text = message;
	}

	@Override
	public boolean insert() throws SQLException {
		return insert(this);
	}
	
	public static boolean insert(Message message) throws SQLException {
		Connection conn = prepareConnection();
		
		PreparedStatement stmt = conn.prepareStatement("INSERT INTO message (user_id, type, date, text) VALUES(?, ?, ?, ?)");
		stmt.setInt(1, 0 /*message.getUser().getId()*/);
		stmt.setString(2, message.getType().toString());
		stmt.setTimestamp(3, message.getDate());
		stmt.setString(4, message.getText());
		
		return stmt.execute();
	}
}
